import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Empty} from 'antd';
import {fileApi} from './constants';
import qs from 'qs';
import {isArray} from 'util';
import {formatMessage} from './intl';
import placholderImage from './400x300.png';
import throttle from 'lodash/throttle';

const contentStyle = {
    height: '100vh'
};
const imgWrappStyle = {
    width: '400px',
    height: '300px',
    display: 'inline-block',
    margin: '16px'
};

const imgStyle = {
    maxWidth: '100%',
    maxHeight: '100%'
};

const emptyStyle = {
    paddingTop: '200px'
};

class App extends Component {
  state = {
      fileList: []
  };

  componentDidMount() {
      const queryString = window.location.hash.split('?')[1];
      const params = qs.parse(queryString, {parseArrays: true});
      const fileList = isArray(params.fileList)
          ? params.fileList
          : [params.fileList];
      const imageReg = new RegExp(/\.(gif|png|jpg|jpeg)$/i);
      const images = fileList
          .filter(file => file)
          .map(file => {
              const fileInfo = file.split(':');
              return {
                  id: fileInfo[0],
                  name: fileInfo[1]
              };
          })
          .filter(file => imageReg.test(file.name));
      this.setState({
          fileList: images
      }, () => {
          this.throttledHandleImageLoad();
      });
      window.addEventListener('scroll', this.throttledHandleImageLoad, true);
  }
  componentWillUnmount() {
      window.removeEventListener('scroll', this.throttledHandleImageLoad);
  }
  isInSight = imgElement => {
      const bound = imgElement.getBoundingClientRect();
      const clientHeight = window.innerHeight;
      return bound.top > 0 && bound.top <= clientHeight + 100;
  };
  loadImg = imgElement => {
      const source = imgElement.dataset.src;
      if(imgElement.src !== source)
          imgElement.src = source;
  };
  
  handleImageLoad = () => {
      const imgs = document.querySelectorAll('.imageWrap img');
      Array.from(imgs).forEach(el => {
          if(this.isInSight(el)) this.loadImg(el);
      });
  };

  throttledHandleImageLoad = throttle(this.handleImageLoad, 500);
  render() {
      return (
          <div className="page-main" style={contentStyle}>
              {this.state.fileList.length > 0 ? (
                  this.state.fileList.map(file => (
                      <div className="imageWrap" style={imgWrappStyle} key={file.id}>
                          <a href={`${fileApi}/${file.id}`}>
                              <img
                                  style={imgStyle}
                                  alt={file.name}
                                  src={placholderImage}
                                  data-src={`${fileApi}/${file.id}`}/>
                          </a>
                      </div>
                  ))
              ) : (
                  <div style={emptyStyle}>
                      <Empty
                          description={formatMessage({
                              id: 'app.fileList.empty',
                              defaultMessage: '暂无图片'
                          })}/>
                  </div>
              )}
          </div>
      );
  }
}

App.propTypes = {
    history: PropTypes.object,
    init: PropTypes.func,
    location: PropTypes.object,
    match: PropTypes.object,
    notification: PropTypes.object
};

export default App;
